﻿using AutoMapper;
using InitQ.Cache;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using SkiaSharp;
using Smart.Admin.Domain.Common;
using Smart.Admin.Domain.Model.Config;
using Smart.Admin.Domain.Model.Const;
using Smart.Admin.Domain.Model.Entity;
using Smart.Admin.Domain.Model.Enum;
using Smart.Admin.Domain.Model.Request.Account;
using Smart.Admin.Domain.Model.Request.Department;
using Smart.Admin.Domain.Model.Request.Employee;
using Smart.Admin.Domain.Model.Request.Menu;
using Smart.Admin.Domain.Model.Request.Role;
using Smart.Admin.Domain.Model.Response;
using Smart.Admin.Domain.Model.Response.Account;
using Smart.Admin.Domain.Model.Response.Department;
using Smart.Admin.Domain.Model.Response.Employee;
using Smart.Admin.Domain.Model.Response.Menu;
using Smart.Admin.Domain.Model.Response.Role;
using Smart.Admin.Domain.Repository;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Smart.Admin.Domain.Service
{
    /// <summary>
    /// 菜单服务
    /// </summary>
    public class MenuService : EmployeeExtensions
    {
        private readonly SmartAdminDbContext _context;
        private readonly ICacheService _redisService;
        private readonly IOptions<JwtOptions> _options;
        private readonly IMapper _mapper;
        public MenuService(SmartAdminDbContext context, ICacheService redisService, IOptions<JwtOptions> options, IMapper mapper)
        {
            _context = context;
            _redisService = redisService;
            _options = options;
            _mapper = mapper;
        }



        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResponse<List<MenuResponse>>> GetMenuList(GetMenuListRequest request)
        {
            try
            {
                var query = from menu in _context.Menu
                            orderby menu.Sort
                            where !menu.DisabledFlag && !menu.DeletedFlag
                            select new MenuResponse()
                            {
                                FrameFlag = menu.FrameFlag,
                                FrameUrl = menu.FrameUrl,
                                CacheFlag = menu.CacheFlag,
                                DisabledFlag = menu.DisabledFlag,
                                VisibleFlag = menu.VisibleFlag,
                                ApiPerms = menu.ApiPerms,
                                Component = menu.Component,
                                ContextMenuId = menu.ContextMenuId,
                                Icon = menu.Icon,
                                MenuId = menu.Id,
                                MenuName = menu.MenuName,
                                MenuType = menu.MenuType,
                                ParentId = menu.ParentId,
                                Path = menu.Path,
                                PermsType = menu.PermsType,
                                Sort = menu.Sort,
                                WebPerms = menu.WebPerms,
                            };
                var responses = await query.ToListAsync();
                return JsonResult.Success(responses);
            }
            catch (Exception ex)
            {
                return JsonResult.Error<List<MenuResponse>>(message: "系统错误");
            }
        }



        /// <summary>
        /// 获取菜单列表(树形结构)
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResponse<List<GetMenuTreeResponse>>> GetMenuTree(GetMenuTreeRequest request)
        {
            try
            {
                //查询全部菜单
                var query = from menu in _context.Menu
                            orderby menu.Sort
                            where !menu.DisabledFlag && !menu.DeletedFlag
                            select new GetMenuTreeResponse()
                            {
                                FrameFlag = menu.FrameFlag,
                                FrameUrl = menu.FrameUrl,
                                CacheFlag = menu.CacheFlag,
                                DisabledFlag = menu.DisabledFlag,
                                VisibleFlag = menu.VisibleFlag,
                                ApiPerms = menu.ApiPerms,
                                Component = menu.Component,
                                ContextMenuId = menu.ContextMenuId,
                                Icon = menu.Icon,
                                MenuId = menu.Id,
                                MenuName = menu.MenuName,
                                MenuType = menu.MenuType,
                                ParentId = menu.ParentId,
                                Path = menu.Path,
                                PermsType = menu.PermsType,
                                Sort = menu.Sort,
                                WebPerms = menu.WebPerms,
                            };
                query = query.WhereIf(request.OnlyMenu, m => m.MenuType <= 2);

                var list = await query.ToListAsync();
                var menuTreeList = list.Where(m => m.ParentId == 0).ToList() ?? new List<GetMenuTreeResponse>();
                for (int i = 0; i < menuTreeList.Count; i++)
                {
                    menuTreeList[i] = BuildTreeMenu(list, menuTreeList[i]);
                }
                return JsonResult.Success(menuTreeList);
            }
            catch (Exception ex)
            {
                return JsonResult.Error<List<GetMenuTreeResponse>>(message: "系统错误");
            }
        }



        /// <summary>
        /// 创建菜单
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<JsonResponse> CreateMenu(CreateMenuRequest request)
        {
            try
            {
                var model = _mapper.Map<MenuEntity>(request);
                model.CreateTime = DateTime.Now;
                model.CreateUserId = Convert.ToInt64(EmployeeId);
                model.UpdateTime = model.CreateTime;
                await _context.Menu.AddAsync(model);
                await _context.SaveChangesAsync();
                return JsonResult.Success();
            }
            catch (Exception ex)
            {
                return JsonResult.Error(message: "系统错误");
            }
        }


        /// <summary>
        /// 修改菜单
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<JsonResponse> UpdateMenu(UpdateMenuRequest request)
        {
            try
            {
                var model = await _context.Menu.FirstOrDefaultAsync(m => m.Id == request.MenuId);
                if (model == null) return JsonResult.Error(message: "数据不存在");
                model.FrameFlag = request.FrameFlag;
                model.FrameUrl = request.FrameUrl;
                model.CacheFlag = request.CacheFlag;
                model.DisabledFlag = request.DisabledFlag;
                model.VisibleFlag = request.VisibleFlag;
                model.ApiPerms = request.ApiPerms;
                model.Component=request.Component;
                model.ContextMenuId=request.ContextMenuId;
                model.Icon=request.Icon;
                model.MenuName=request.MenuName;
                model.MenuType=request.MenuType;
                model.ParentId=request.ParentId;
                model.Path=request.Path;
                model.PermsType=request.PermsType;
                model.Sort =request.Sort;
                model.UpdateUserId=Convert.ToInt64(EmployeeId);
                model.WebPerms=request.WebPerms;
                model.UpdateTime = DateTime.Now;
                _context.Menu.Update(model);
                await _context.SaveChangesAsync();
                return JsonResult.Success();
            }
            catch (Exception ex)
            {
                return JsonResult.Error(message: "系统错误");
            }
        }

        /// <summary>
        /// 删除菜单(逻辑)
        /// </summary>
        /// <param name="menuId"></param>
        /// <returns></returns>
        public async Task<JsonResponse> DeleteMenu(DeleteMenuRequest request)
        {
            try
            {
                if(request==null || request.MenuIdList==null) return JsonResult.Error(message: "参数错误");
                var list = new List<MenuEntity>();
                foreach (var menuId in request.MenuIdList)
                {
                    var model = await _context.Menu.FirstOrDefaultAsync(m => m.Id == menuId);
                    if (model!=null) 
                    {
                        model.DeletedFlag = true;
                        list.Add(model);
                    }
                }
                if (list.Count > 0)
                {
                    _context.Menu.UpdateRange(list);
                    await _context.SaveChangesAsync();
                }
                return JsonResult.Success();
            }
            catch (Exception ex)
            {
                return JsonResult.Error(message: "系统错误");
            }
        }



        /// <summary>
        /// 递归构建菜单
        /// </summary>
        /// <param name="list"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        private GetMenuTreeResponse BuildTreeMenu(List<GetMenuTreeResponse> list, GetMenuTreeResponse model)
        {
            model.Children = list.Where(m => m.ParentId == model.MenuId).OrderByDescending(p => p.Sort).ToList();
            if (model.Children != null && model.Children.Count() != 0)
            {
                for (int i = 0; i < model.Children.Count(); i++)
                {
                    var child = model.Children[i];
                    child = BuildTreeMenu(list, child);
                }
            }
            return model;
        }

    }
}
